<template>
	<el-dialog :title="form.id ? '编辑' : '新增'" :visible.sync="visible" :close-on-click-modal="false">
		<el-form ref="form" :model="form" :rules="rules">
			<el-form-item label="课件分类" :label-width="formLabelWidth" v-if="form.id">
				<el-select v-model="form.classifyId" clearable placeholder="请选择" v-if="form.id">
					<el-option :label="selLeftTree.name" :value="selLeftTree.id">
						<el-tree
							:data="leftTreeData"
							:props="{
								children: 'children',
								label: 'name',
							}"
							accordion
							highlight-current
							@node-click="handleSelectionChange"
						></el-tree>
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="课件类型" :label-width="formLabelWidth" prop="coursewareType">
				<fortress-radio-group v-model="form.coursewareType" :dictList="CoursewareTypeList"></fortress-radio-group>
			</el-form-item>
			<el-form-item label="课件名称" :label-width="formLabelWidth" prop="coursewareName">
				<el-input v-model="form.coursewareName" autocomplete="off" placeholder="请输入课件名称" maxlength="100" show-word-limit></el-input>
			</el-form-item>
			<el-form-item label="学习时长" :label-width="formLabelWidth" prop="studyTime">
				<el-input-number :step="1" step-strictly v-model="form.studyTime"></el-input-number>
				分钟
			</el-form-item>
			<!-- <el-form-item label="课件大小" :label-width="formLabelWidth" prop="coursewareSize">
				<el-input v-model="form.coursewareSize" autocomplete="off" placeholder="请输入课件大小"></el-input>
			</el-form-item> -->
			<el-form-item label="视频课件简介" :label-width="formLabelWidth" prop="videoSynopsis" v-if="form.coursewareType == 3">
				<el-input type="textarea" :rows="2" placeholder="请输入视频课件简介" v-model="form.videoSynopsis" maxlength="200" show-word-limit></el-input>
			</el-form-item>
			<el-form-item label="课件地址" :label-width="formLabelWidth" prop="coursewareUrl" v-if="form.coursewareType == 3" key="video">
				<fortress-upload @upload-success="onFileUploadSuccess" :size="1024" type="video" :limit="1" name="coursewareUrl" :formData="form"></fortress-upload>
			</el-form-item>
			<el-form-item label="课件地址" :label-width="formLabelWidth" prop="originUrl" v-if="form.coursewareType == 1" key="file">
				<!-- <fortress-upload :size="1024" type="file" :limit="1" name="originUrl" :formData="form" @upload-success="onFileUploadSuccess"></fortress-upload> -->
				<upload-file :fileSize="1024" v-model="form.originUrl" :coursewareName="form.coursewareName" @changeName="changeName"></upload-file>
			</el-form-item>
			<el-form-item label="图文正文" :label-width="formLabelWidth" prop="coursewareContent" v-if="form.coursewareType == 2">
				<fortress-editor v-model="form.coursewareContent"></fortress-editor>
			</el-form-item>
			<!-- <el-form-item label="是否允许下载" :label-width="formLabelWidth" prop="isDownload">
				<el-switch
					v-model="form.isDownload"
					active-color="#13ce66"
					inactive-color="#ff4949"
					:active-value="1"
					:inactive-value="2"
				></el-switch>
			</el-form-item> -->
			<el-form-item label="排序" :label-width="formLabelWidth" prop="sort">
				<template #label>
					<span style="margin-right: 7px;">排序</span>
					<el-tooltip class="item" effect="dark" content="数字越大越靠前" placement="top">
						<i class="el-icon-info"></i>
					</el-tooltip>
				</template>
				<el-input-number v-model="form.sort"></el-input-number>
			</el-form-item>
		</el-form>
		<div slot="footer" class="dialog-footer">
			<el-button @click="visible = false" size="medium" type="danger">取 消</el-button>
			<el-button type="primary" size="medium" @click="submitForm('form')">确 定</el-button>
		</div>
	</el-dialog>
</template>
<script>
import { studycoursewareInfo, studycoursewareSave, studycoursewareEdit } from "@/api/study/course/studycourseware.js"
import { enumList, urlList } from "@/api/public.api.js"
import uploadFile from "../../../components/fortress-upload/upload-file.vue"

export default {
	props: ["leftTreeData"],
	data() {
		return {
			visible: false,
			selLeftTree: {},
			form: {
				classifyId: "",
				coursewareType: 1,
				coursewareName: "",
				studyTime: "",
				coursewareSize: "",
				videoSynopsis: "",
				originUrl: [],
				coursewareUrl: [],
				coursewareContent: "",
				isDownload: "2",
				sort: "",
				classifyIdName: "",
			},
			formLabelWidth: "120px",
			myconfig: window.$conf.commonConf.ueConfig,
			rules: {
				classifyId: [{ required: true, message: "请输入课件分类", trigger: "change" }],
				coursewareType: [{ required: true, message: "请输入课件类型", trigger: "change" }],
				coursewareName: [{ required: true, message: "请输入课件名称", trigger: "change" }],
				isDownload: [{ required: true, message: "请输入是否允许下载", trigger: "change" }],
				originUrl: [{ required: true, message: "请上传课件地址", trigger: "change" }],
				coursewareUrl: [{ required: true, message: "请上传课件地址", trigger: "change" }],
			},
			CoursewareTypeList: [],
			YesNoList: [],
			classifyIdList: [],
		}
	},
	created() {},
	methods: {
		/**
		 *
		 * @param {[any, File]} param0
		 */
		onFileUploadSuccess([_res, file]) {
			if (this.form.coursewareName == "" || this.form.coursewareName == null) {
				const fileName = file.name.split(".")
				fileName.pop()
				this.form.coursewareName = fileName.join(".")
			}

			if (this.form.coursewareType == 3) {
				if (!this.form.studyTime) {
					this.getVideoDuration(file.raw).then(res => {
						this.form.studyTime = Math.ceil((res / 60) | 0)
					})
				}
			}
			this.$nextTick(() => {
				this.$refs["form"].validate()
			})
		},
		getVideoDuration(file) {
			return new Promise((resolve, reject) => {
				const video = document.createElement("video")
				video.preload = "metadata"
				video.onloadedmetadata = () => {
					window.URL.revokeObjectURL(video.src)
					const duration = video.duration
					resolve(duration)
				}
				video.onerror = () => {
					window.URL.revokeObjectURL(video.src)
					reject(new Error("Error loading video"))
				}
				const fileURL = window.URL.createObjectURL(file)
				video.src = fileURL
			})
		},
		queryEnumList() {
			this.CoursewareTypeList = []
			enumList("CoursewareType", "").then(resp => {
				if (resp.code == 0) {
					this.CoursewareTypeList = resp.data
				}
			})
			this.YesNoList = []
			enumList("YesNo", "").then(resp => {
				if (resp.code == 0) {
					this.YesNoList = resp.data
				}
			})
		},
		queryUrlList() {
			this.classifyIdList = []
			urlList("/study/course/studyCourseClassify/list").then(resp => {
				if (resp.code == 0) {
					if (resp.data) {
						resp.data.forEach(item => {
							this.classifyIdList.push({ code: item.id, name: item.name })
						})
					}
				}
			})
		},
		init(id, treeId, treeName) {
			this.resetForm()
			this.queryEnumList()
			this.queryUrlList()
			//修改
			if (id) {
				studycoursewareInfo(id).then(resp => {
					if (resp.code == 0) {
						this.$nextTick(() => {
							if (resp.data.originUrl) {
								let originUrlArray = JSON.parse(resp.data.originUrl)
								resp.data.originUrl = []
								originUrlArray.forEach(item => {
									resp.data.originUrl.push({ name: item.name, url: item.url })
									this.form.coursewareName = item.name
								})
							}
							if (resp.data.coursewareUrl) {
								if (Array.isArray(resp.data.coursewareUrl) && resp.data.coursewareUrl.indexOf("[") == -1) {
									// console.log(1)
								} else {
									let coursewareUrlArray = JSON.parse(resp.data.coursewareUrl)
									resp.data.coursewareUrl = []
									coursewareUrlArray.forEach(item => {
										resp.data.coursewareUrl.push({ name: item.name, url: item.url })
									})
								}
							}
							this.selLeftTree = {
								id: resp.data.classifyId,
								name: resp.data.classifyIdName,
							}
							this.form = {
								...this.form,
								...resp.data,
							}

							console.log(this.form)
						})
					} else {
						this.$msg({
							message: resp.msg,
							type: "error",
						})
					}
				})
			} else {
				this.form.coursewareType = 1
				this.form.classifyId = treeId
				this.selLeftTree = {
					id: treeId,
					name: treeName,
				}
			}
			this.visible = true
		},
		//提交表单数据
		submitForm() {
			this.$refs["form"].validate(valid => {
				if (valid) {
					const params = Object.assign({}, this.form)
					if (params.originUrl) {
						console.log(params.originUrl, "params.originUrl")
						let originUrlJson = []
						if (Array.isArray(params.originUrl)) {
							params.originUrl.forEach(item => {
								originUrlJson.push({ name: item.name, url: item.url })
							})
						} else {
							originUrlJson.push({ name: params.originUrl.name, url: params.originUrl.url })
						}
						params.originUrl = JSON.stringify(originUrlJson)
					}
					if (!params.coursewareUrl) {
						params.coursewareUrl = params.originUrl
					} else {
						let coursewareUrlJson = []
						params.coursewareUrl.forEach(item => {
							coursewareUrlJson.push({ name: item.name, url: item.url })
						})
						params.coursewareUrl = JSON.stringify(coursewareUrlJson)
					}
					//修改
					if (params.id) {
						studycoursewareEdit(params).then(resp => {
							if (resp.code == 0) {
								this.$message({
									type: "success",
									message: "操作成功!",
								})
								this.$emit("refreshData")
								this.visible = false
							} else {
								this.$msg({
									message: resp.msg,
									type: "error",
								})
							}
						})
						//新增
					} else {
						studycoursewareSave(params).then(resp => {
							if (resp.code == 0) {
								this.$message({
									type: "success",
									message: "操作成功!",
								})
								this.$emit("refreshData")
								this.visible = false
							} else {
								this.$msg({
									message: resp.msg,
									type: "error",
								})
							}
						})
					}
				} else {
					console.log("error submit!!")
					return false
				}
			})
		},
		resetForm() {
			this.form = {
				classifyId: "",
				coursewareType: "",
				coursewareName: "",
				studyTime: "",
				coursewareSize: "",
				videoSynopsis: "",
				originUrl: [],
				coursewareUrl: [],
				coursewareContent: "",
				isDownload: "2",
				sort: "",
				classifyIdName: "",
			}
			this.$nextTick(() => {
				if (this.$refs["form"]) {
					this.$refs["form"].resetFields()
				}
			})
		},
		//切换树数据选中状态
		handleSelectionChange(data) {
			this.selLeftTree.id = data.id
			this.selLeftTree.name = data.name
			this.form.classifyId = data.id
		},
		changeName(name) {
			this.form.coursewareName = name
		},
	},
	components: {
		uploadFile,
	},
}
</script>
<style scoped>
.avatar-uploader .el-upload {
	border: 1px dashed #d9d9d9;
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
}
.avatar-uploader .el-upload:hover {
	border-color: #409eff;
}
.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	line-height: 178px;
	text-align: center;
}
.avatar {
	width: 178px;
	height: 178px;
	display: block;
}
.el-scrollbar .el-scrollbar__view .el-select-dropdown__item {
	height: auto;
	max-height: 274px;
	padding: 7px;
	overflow: hidden;
	overflow-y: auto;
	font-weight: normal;
}
</style>
